package com.woohua.thread.completefeature;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/***
 * @title AndTask
 * @description：合并任务结果
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/21 10:01
 **/
public class AndTask {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 10. thenCombine 合并A，B结果，并返回
        CompletableFuture<String> future10 = CompletableFuture.supplyAsync(() -> {
            sleep(100);
            return "10.1 TaskA return value";
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
            sleep(100);
            return "10.2 TaskB return value";
        }), (taskAReturnVal, taskBReturnVal) -> taskAReturnVal + taskBReturnVal);
        System.out.println("10.3 get: " + future10.get());

        // 11.thenAcceptBoth 合并A，B结果，无返回
        CompletableFuture.supplyAsync(() -> {
            sleep(100);
            return "11.1 TaskA return value";
        }).thenAcceptBoth(CompletableFuture.supplyAsync(() -> {
            sleep(100);
            return "11.2 TaskB return value";
        }), (taskAReturnVal, taskBReturnVal) -> {
            System.out.println(taskAReturnVal + taskBReturnVal);
        });
        sleep(200);

        // 12. returnAfterBoth A,B都执行完后才执行C, C不关心前面任务的返回值
        CompletableFuture.supplyAsync(() -> {
            sleep(200);
            System.out.println("12.1 TaskA be called.");
            return "12.2 TaskA return value";
        }).runAfterBoth(CompletableFuture.supplyAsync(() -> {
            sleep(100);
            System.out.println("12.3 TaskB be called");
            return "12.4 TaskB return value";
        }), () -> {
            System.out.println("12.5 TaskC be called");
        });
        sleep(300);
    }

    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
